$(document).ready(function () {

    $(".showTime").each(function(){
        var reg = new RegExp( ',' , "g" )
        $(this).text(formatDate(parseInt($(this).text().replace(reg,""))));
    });
    function formatDate(str) {
        var now=new Date(str*1000);
        var year=now.getFullYear();
        var month=now.getMonth()+1;
        var date=now.getDate();
        var hour=now.getHours();
        var minute=now.getMinutes();
        var second=now.getSeconds();
        return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
    }
    var uuid = $("#text-uuid").html();

    // 初始化刷新运行状态
    refreshStatus();

    // 部署按钮
    $("#btn-deploy").click(function () {
        deployData("../deploy/" + uuid);
    });

    // 重启按钮
    $("#btn-restart").click(function () {
        ajaxShell("../restart", {uuid: uuid}, function () {
            refreshStatus();
        });
    });

    // 停止按钮
    $("#btn-stop").click(function () {
        ajaxShell("../stop", {uuid: uuid}, function () {
            refreshStatus();
        });
    });

    // 停止按钮
    $("#btn-remove").click(function () {
        ajaxShell("../remove", {uuid: uuid}, function () {
            refreshStatus();
        });
    });


    //查看日志
    $(".log").click(function () {
        deployLog($(this).attr("data"))
    });

    //下载
    $(".download").click(function () {
        location.href = "/deploy/downloadLog/" + $(this).attr("data")
    });

    $(".rollback").click(function () {
        rollBack("/deploy/rollback/" + uuid + "/" + $(this).attr("data"));
    });

    //删除
    $(".remove").click(function () {
        location.href = "/deploy/remove/" + $(this).attr("data")
    });

    /**
     * ajax请求后台运行脚本
     */
    function ajaxShell(url, postData, successCallback) {
        $("#loader-modal").openModal({dismissible: false});
        $.ajax({
            url: url,
            type: "POST",
            data: postData,
            cache: false,
            dataType: "text",
            success: function (data) {
                $("#loader-modal").closeModal();
                $("#layer-modal .modal-content").html(data.replace(/\n/g, "<br>"));
                $("#layer-modal").openModal({dismissible: false});
                if (successCallback) {
                    successCallback();
                }
            },
            error: function () {
                $("#loader-modal").closeModal();
                layerAlert("发生异常，请重试！");
            }
        });
    }

    function deployLog(recordId) {
        var url = "ws://" + location.host + "/ws";
        var websocket = new WebSocket(url);
        websocket.onmessage = function (event) {
            var msg = event.data;
            var s = JSON.parse(msg);
            if (s.type == "record") {
                $("#layer-modal .modal-content>div").html(s.msg);
            }
        };
        websocket.onopen = function (event) {
            if (recordId != null) {
                //向服务器订阅部署消息
                websocket.send("{\"record_id\":\"" + recordId + "\",\"type\":\"log\"}")
            }
        }
        $("#layer-modal .modal-content").html("<div></div>");
        $("#layer-modal").openModal({
            dismissible: false,
            complete: function () {
                websocket.close();
            }
        });
    }

    function deployData(url, postData) {
        $("#loader-modal").openModal({dismissible: false});
        $.ajax({
            url: url,
            type: "POST",
            cache: false,
            success: function (data) {
                $("#loader-modal").closeModal();
                deployLog(data.recordId);
            },
            error: function () {
                $("#loader-modal").closeModal();
                layerAlert("发生异常，请重试！");
            }
        });
    }


    /**
     * 刷新服务器运行状态
     */
    function refreshStatus() {
        $.ajax({
            url: "../status",
            type: "POST",
            data: {uuid: uuid},
            cache: false,
            success: function (data) {
                var res = "状态：" + data.data.status + "<br>";
                res += "镜像ID：" + data.data.imageId + "<br>";
                res += "容器ID：" + data.data.id + "<br>";
                res += "日志路径：" + data.data.logPath + "<br>";
                res += "创建时间：" + data.data.created + "<br>";
                $(".service-status").find(".green-text").html(res).show();
            },
            error: function () {
                layerAlert("发生异常，请重试！");
            }
        });
    }


    function rollBack(Url) {
        $.ajax({
            url: Url,
            type: "GET",
            cache: false,
            success: function (data) {
                location.reload();
            },
            error: function () {
                layerAlert("发生异常，请重试！");
            }
        });
    }


    /**
     * 用于代替alert
     * @param text
     */
    function layerAlert(text) {
        $("#alert-modal .text-alert").html(text);
        $("#alert-modal").openModal({dismissible: false});
    }

});